<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px">
      <el-form-item label="模型名称" prop="modelName">
        <el-input v-model="queryParams.modelName" placeholder="请输入模型名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="省" prop="province">
        <el-select v-model="queryParams.province" placeholder="请选择省" @change="chooseProvince" clearable>
          <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="市" prop="city">
        <el-select v-model="queryParams.city" placeholder="请选择市" @change="chooseCity" clearable>
          <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label=" ">
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button plain @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="casualtiesList" stripe>
      <el-table-column label="模型名称" align="center" prop="modelName">
        <template #default="scope">
          <el-button type="text" @click="edit(scope.row)">{{
            scope.row.modelName
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="省" align="center" prop="province" />
      <el-table-column label="市" align="center" prop="city" />
      <el-table-column label="是否默认" align="center" prop="isDefault">
        <template #default="scope">
          <span v-if="scope.row.isDefault == '0'">否</span>
          <span v-if="scope.row.isDefault == '1'">是</span>
        </template>
      </el-table-column>
      <el-table-column label="维护人" align="center" prop="createUserName" />
      <el-table-column label="维护人所属单位" align="center" prop="orgName" />
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
      @pagination="getList" />

    <el-dialog :title="title" v-model="open" width="850px" append-to-body custom-class="casualties-model-dialog" destroy-on-close>
      <el-scrollbar>
        <el-form ref="casualtiesRef" :model="form" :rules="rules" label-width="120px" scroll-to-error>
          <p class="dialogTitle">{{ title }}</p>
          <el-row>
            <el-col :span="12">
              <el-form-item label="模型名称" prop="modelName" v-if="isCopy">
                {{ form.modelName }}
              </el-form-item>
              <el-form-item label="模型名称" prop="modelName" v-else>
                <el-input v-model="form.modelName" placeholder="请输入模型名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否默认" prop="isDefault" v-if="isCopy">
                {{ form.isDefault == '0' ? '否' : '是' }}
              </el-form-item>
              <el-form-item label="是否默认" prop="isDefault" v-else>
                <el-select v-model="form.isDefault" disabled style="width: 100%;">
                  <el-option v-for="item in [
                    { value: 0, label: '否' },
                    { value: 1, label: '是' },
                  ]" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="地区" prop="" v-if="isCopy || isEditDefault">
                {{ form.provinceName }} - {{ form.cityName || form.city }}
              </el-form-item>
              <el-form-item label="地区" prop="" v-else>
                <el-form-item label="省" prop="provinceId" label-width="50px">
                  <el-select v-model="form.provinceId" placeholder="请输入省" @change="chooseFormProvince"
                    style="width: 160px;">
                    <el-option v-for="item in provinceFormData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-col :span="16">
                  <el-form-item label="市" prop="cityId" label-width="50px">
                    <el-radio-group v-model="radio" @change="chooseRadio">
                      <el-radio label="1">全部</el-radio>
                      <el-radio label="2">
                        <el-select v-model="form.cityId" placeholder="请输入市" multiple collapse-tags :disabled="isCityEdit"
                          style="width: 200px;">
                          <el-option v-for="item in cityFormData" :key="item.id" :label="item.name" :value="item.id">
                          </el-option>
                        </el-select>
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="维护人" prop="createUserName">
                {{ form.createUserName }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="维护人单位" prop="orgName">
                {{ form.orgName }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider></el-divider>
          <el-row justify="center">
            <el-col :span="22" style="text-indent: 4ch;line-height: 1.5rem;">
              首先将结构分为三类，即第Ⅰ类：住宅、公寓、学生和职工集体宿舍、宾馆、招待所等人员居住场所；第Ⅱ类：办公室、生产车间、教室等工作与学习场所；第Ⅲ类为娱乐场所、体育馆、车站、候机室、码头等人员较集中的公共场所。式5、6分别给出了人员伤亡估算模型：
            </el-col>
          </el-row>
          <el-row justify="space-around">
            <el-col :span="12">
              <p><vue-latex :expression="'M_d(I)=Cη(A_1r_{d1}+A_2r_{d2}+A_3r_{d3})'" /></p>
            </el-col>
            <el-col :span="2"><p><vue-latex :expression="'(1)'" /></p></el-col>
          </el-row>
          <el-row justify="space-around">
            <el-col :span="12">
              <p><vue-latex :expression="'M_h(I)=Cη(A_1r_{h1}+A_2r_{h2}+A_3r_{h3}+A_4r_{h4})'" /></p>
            </el-col>
            <el-col :span="2"><p><vue-latex :expression="'(2)'" /></p></el-col>
          </el-row>
          <el-row justify="center">
            <el-col :span="12">
              <p>式中：</p>
              <p><vue-latex :expression="'M_d(I)'" /> —— 估计当地震动输入为I时的死亡人数；</p>
              <p><vue-latex :expression="'M_h(I)'" /> —— 估计当地震动输入为I时的重伤人数；</p>
              <p><vue-latex :expression="'C'" /> —— 地震时人员在室内的百分比；</p>
              <p><vue-latex :expression="'A_1'" /> —— 毁坏房屋的面积；</p>
              <p><vue-latex :expression="'A_2'" /> —— 严重破坏房屋的面积；</p>
              <p><vue-latex :expression="'A_3'" /> —— 中等破坏房屋的面积；</p>
              <p><vue-latex :expression="'A_4'" /> —— 轻微破坏房屋的面积；</p>
              <p><vue-latex :expression="'η'" /> —— 房屋内人员的密度；</p>
              <p><vue-latex :expression="'r_{d1}'" />，<vue-latex :expression="'r_{h1}'" /> —— 分别是毁坏房屋内的死亡率和重伤率；</p>
              <p><vue-latex :expression="'r_{d2}'" />，<vue-latex :expression="'r_{h2}'" /> —— 分别是严重破坏房屋内的死亡率和重伤率；</p>
              <p><vue-latex :expression="'r_{d3}'" />，<vue-latex :expression="'r_{h3}'" /> —— 分别是中等破坏房屋内的死亡率和重伤率；</p>
              <p><vue-latex :expression="'r_{h4}'" /> —— 是轻微破坏房屋内的重伤率；</p>
            </el-col>
          </el-row>
          <el-row justify="center">
            <el-col :span="22" style="text-indent: 4ch;line-height: 1.5rem;">
              为了使用公式（1）、（2），该方法分五个时间段给出了一昼夜不同时间人员在不同空间位置的百分比，表1是修改后按夜间和白天分别给出的百分比，表2给出了不同结构破坏时室内人员伤亡率的估算值。
            </el-col>
          </el-row>
          <el-row justify="center">
            <el-col :span="22">
              <div style="margin-top:10px;line-height: 30px;">
                <table align="center" style="width: 100%;border-collapse: collapse;" class="casualtiesTable">
                  <caption>表1 室内人员昼夜在不同空间位置的百分比</caption>
                  <tr>
                    <th id="lineTd" align="center">
                      <span style="float:left;margin: 20px 0 0 10px;">房屋类别</span>
                      <span style="float:right;margin: 0 10px 0 0">时间</span>
                    </th>
                    <th align="center">夜间</th>
                    <th align="center">白天</th>
                  </tr>
                  <tr>
                    <td style="width: 100px;" align="center" valign="middle">Ⅰ类</td>
                    <td style="width: 100px;" align="center" valign="middle">
                      <div v-if="isCopy"> {{ form.nightClass1 }} </div>
                      <div v-else>
                        <el-form-item prop="nightClass1" label-width="0px">
                          <el-input v-model="form.nightClass1" v-inputNumber="6"></el-input>
                        </el-form-item>
                      </div>
                    </td>
                    <td style="width: 100px;" align="center" valign="middle">
                      <div v-if="isCopy"> {{ form.dayClass1 }} </div>
                      <div v-else>
                        <el-form-item prop="dayClass1" label-width="0px">
                          <el-input v-model="form.dayClass1" v-inputNumber="6"></el-input>
                        </el-form-item>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <td style="width: 100px;" align="center" valign="middle">Ⅱ类</td>
                    <td style="width: 100px;" align="center" valign="middle">
                      <div v-if="isCopy"> {{ form.nightClass2 }} </div>
                      <div v-else>
                        <el-form-item prop="nightClass2" label-width="0px">
                          <el-input v-model="form.nightClass2" v-inputNumber="6"></el-input>
                        </el-form-item>
                      </div>
                    </td>
                    <td style="width: 100px;" align="center" valign="middle">
                      <div v-if="isCopy"> {{ form.dayClass2 }} </div>
                      <div v-else>
                        <el-form-item prop="dayClass2" label-width="0px">
                          <el-input v-model="form.dayClass2" v-inputNumber="6"></el-input>
                        </el-form-item>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <td style="width: 100px;" align="center" valign="middle">Ⅲ类</td>
                    <td style="width: 100px;" align="center" valign="middle">
                      <div v-if="isCopy"> {{ form.nightClass3 }} </div>
                      <div v-else>
                        <el-form-item prop="nightClass3" label-width="0px">
                          <el-input v-model="form.nightClass3" v-inputNumber="6"></el-input>
                        </el-form-item>
                      </div>
                    </td>
                    <td style="width: 100px;" align="center" valign="middle">
                      <div v-if="isCopy"> {{ form.dayClass3 }} </div>
                      <div v-else>
                        <el-form-item prop="dayClass3" label-width="0px">
                          <el-input v-model="form.dayClass3" v-inputNumber="6"></el-input>
                        </el-form-item>
                      </div>
                    </td>
                  </tr>
                </table>
              </div>
            </el-col>
          </el-row>
          <el-row justify="center">
            <el-col :span="22">
              <div style="margin-top:10px;line-height: 30px;">
                <table align="center" style="width: 100%;border-collapse: collapse;" class="casualtiesTable">
                  <caption>表2 结构不同破坏程度下室内人员的伤亡率</caption>
                  <tr>
                    <th align="center">破坏状态</th>
                    <th align="center">重伤率</th>
                    <th align="center">死亡率</th>
                  </tr>
                  <tr>
                    <td style="width: 100px;" align="center" valign="middle">基本完好</td>
                    <td style="width: 100px;" align="center" valign="middle">
                      <div v-if="isCopy"> {{ form.intactInjury }} </div>
                      <div v-else>
                        <el-form-item prop="intactInjury" label-width="0px">
                          <el-input v-model="form.intactInjury" v-inputNumber="6"></el-input>
                        </el-form-item>
                      </div>
                    </td>
                    <td style="width: 100px;" align="center" valign="middle">
                      <div v-if="isCopy"> {{ form.intactDeath }} </div>
                      <div v-else>
                        <el-form-item prop="intactDeath" label-width="0px">
                          <el-input v-model="form.intactDeath" v-inputNumber="6"></el-input>
                        </el-form-item>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <td style="width: 100px;" align="center" valign="middle">轻微破坏</td>
                    <td style="width: 100px;" align="center" valign="middle">
                      <div v-if="isCopy"> {{ form.slightInjury }} </div>
                      <div v-else>
                        <el-form-item prop="slightInjury" label-width="0px">
                          <el-input v-model="form.slightInjury" v-inputNumber="6"></el-input>
                        </el-form-item>
                      </div>
                    </td>
                    <td style="width: 100px;" align="center" valign="middle">
                      <div v-if="isCopy"> {{ form.slightDeath }} </div>
                      <div v-else>
                        <el-form-item prop="slightDeath" label-width="0px">
                          <el-input v-model="form.slightDeath" v-inputNumber="6"></el-input>
                        </el-form-item>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <td style="width: 100px;" align="center" valign="middle">中等破坏</td>
                    <td style="width: 100px;" align="center" valign="middle">
                      <div v-if="isCopy"> {{ form.mediumInjury }} </div>
                      <div v-else>
                        <el-form-item prop="mediumInjury" label-width="0px">
                          <el-input v-model="form.mediumInjury" v-inputNumber="6"></el-input>
                        </el-form-item>
                      </div>
                    </td>
                    <td style="width: 100px;" align="center" valign="middle">
                      <div v-if="isCopy"> {{ form.mediumDeath }} </div>
                      <div v-else>
                        <el-form-item prop="mediumDeath" label-width="0px">
                          <el-input v-model="form.mediumDeath" v-inputNumber="6"></el-input>
                        </el-form-item>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <td style="width: 100px;" align="center" valign="middle">严重破坏</td>
                    <td style="width: 100px;" align="center" valign="middle">
                      <div v-if="isCopy"> {{ form.seriousInjury }} </div>
                      <div v-else>
                        <el-form-item prop="seriousInjury" label-width="0px">
                          <el-input v-model="form.seriousInjury" v-inputNumber="6"></el-input>
                        </el-form-item>
                      </div>
                    </td>
                    <td style="width: 100px;" align="center" valign="middle">
                      <div v-if="isCopy"> {{ form.seriousDeath }} </div>
                      <div v-else>
                        <el-form-item prop="seriousDeath" label-width="0px">
                          <el-input v-model="form.seriousDeath" v-inputNumber="6"></el-input>
                        </el-form-item>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <td style="width: 100px;" align="center" valign="middle">毁坏</td>
                    <td style="width: 100px;" align="center" valign="middle">
                      <div v-if="isCopy"> {{ form.destroyInjury }} </div>
                      <div v-else>
                        <el-form-item prop="destroyInjury" label-width="0px">
                          <el-input v-model="form.destroyInjury" v-inputNumber="6"></el-input>
                        </el-form-item>
                      </div>
                    </td>
                    <td style="width: 100px;" align="center" valign="middle">
                      <div v-if="isCopy"> {{ form.destroyDeath }} </div>
                      <div v-else>
                        <el-form-item prop="destroyDeath" label-width="0px">
                          <el-input v-model="form.destroyDeath" v-inputNumber="6"></el-input>
                        </el-form-item>
                      </div>
                    </td>
                  </tr>
                </table>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="copyForm" v-if="isCopy">复 制</el-button>
          <el-button type="primary" @click="saveForm" v-if="!isCopy && Default == '1'">保 存</el-button>
          <el-button type="primary" @click="editForm" v-if="!isCopy && Default == '0'">保 存</el-button>
          <el-button type="primary" @click="delForm" v-if="!isCopy && Default == '0'">删 除</el-button>
          <el-button plain @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="casualtiesModel">
import { listCasualties, getModelCasualties, delCasualties, addCasualties, updateCasualties } from "@/api/modelManage/casualties"
import { getProvince, getChildArea } from "@/api/system/division"

const { proxy } = getCurrentInstance();

const casualtiesList = ref([]);
const isCopy = ref(true);
const Default = ref("1");
const radio = ref("1");
const isCityEdit = ref(true);
const isEditDefault = ref(true);
const open = ref(false);
const loading = ref(true);
const total = ref(0);
const title = ref("");
const provinceData = ref([]);//省
const cityData = ref([]);//市
const areaData = ref([]);//区、县

const provinceFormData = ref([]);//表单省 
const cityFormData = ref([]);//表单市
const areaFormData = ref([]);//表单区、县

const data = reactive({
  form: {},
  queryParams: {
    page: 1,
    rows: 10,
    province: null,
    city: null
  },
  rules: {
    modelName: [{ required: true, message: "模型名称不能为空", trigger: "blur" }],
    province: [{ required: true, message: "省不能为空", trigger: "blur" }],
    provinceId: [{ required: true, message: "省不能为空", trigger: "change" }],
    city: [{ required: true, message: "市不能为空", trigger: "change" }],
    cityId: [{ required: false, message: "市不能为空", trigger: "change" }],
    area: [{ required: true, message: "区/县不能为空", trigger: "blur" }],
    areaId: [{ required: true, message: "区/县 不能为空", trigger: "blur" }]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 查询人口伤亡计算模型列表
function getList() {
  loading.value = true
  listCasualties(queryParams.value).then(response => {
    casualtiesList.value = response.data.rows
    total.value = response.data.total
    loading.value = false
  })
}

// 获取省市区县列表
function getProvinceData() {
  getProvince().then(response => {
    provinceData.value = response.data
  })
}

function getProvinceFormData() {
  getProvince().then(response => {
    provinceFormData.value = response.data
  })
}

function chooseRadio(value) {
  if (value == "2") {
    isCityEdit.value = false
  } else {
    isCityEdit.value = true
    form.value.city = "全部"
    form.value.cityId = ""
  }
}

function chooseProvince(value) {
  queryParams.value.city = null
  queryParams.value.area = null
  cityData.value = []
  areaData.value = []
  getChildArea(value).then(response => {
    cityData.value = response.data
  })
}

function chooseFormProvince(value) {
  form.value.city = null
  form.value.area = null
  cityFormData.value = []
  areaFormData.value = []
  getChildArea(value).then(response => {
    cityFormData.value = response.data
  });
}

function chooseCity(value) {
  queryParams.value.areaId = null
  areaData.value = []
  getChildArea(value).then(response => {
    areaData.value = response.data
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    modelName: null,
    province: null,
    provinceId: null,
    city: null,
    cityId: null,
    area: null,
    areaId: null,
    isDefault: null
  }
  isCopy.value = true
  proxy.resetForm("casualtiesRef");
}

// 搜索按钮
function handleQuery() {
  queryParams.value.page = 1;
  getList();
}

// 重置按钮
function resetQuery() {
  cityData.value = [];
  areaData.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 查看按钮
const edit = async (row) => {
  reset()
  const id = row.id
  if (row.isDefault == "1") {
    isCopy.value = true
    Default.value = "1"
    title.value = "系统默认人员伤亡计算模型"
  } else {
    isCopy.value = false
    Default.value = "0"
    title.value = "人员伤亡计算模型"
  }
  await getModelCasualties(id).then(response => {
    form.value = response.data
    form.value.provinceId = response.data.province
    if (form.value.provinceId && isCopy.value) {
      getChildArea(form.value.provinceId).then(res => {
        cityFormData.value = res.data
        form.value.cityId = response.data.city?.split(',')
      })
    }
    open.value = true
    if (form.value.city == "全部") {
      radio.value = "1"
      isCityEdit.value = true
    } else {
      radio.value = "2"
      isCityEdit.value = false
    }
    if (form.value.isDefault == "0") {
      isEditDefault.value = true
    } else {
      isEditDefault.value = false
    }
  })
}

// 复制
function copyForm() {
  isCopy.value = false
  form.value.isDefault = "0"
  title.value = "复制人员伤亡计算模型"
}

// 新增
function saveForm() {
  proxy.$refs["casualtiesRef"].validate(valid => {
    if (valid) {
      if (radio.value == "1") {
        form.value.cityId = "全部"
      } else {
        if (form.value.cityId != null) {
          form.value.cityId = JSON.parse(JSON.stringify(form.value.cityId)).join(",")
        }
      }
      const {modelName, isDefault, provinceId, cityId, nightClass1, dayClass1, nightClass2, dayClass2, nightClass3, dayClass3, intactInjury, intactDeath, slightInjury, slightDeath, mediumInjury, mediumDeath, seriousInjury, seriousDeath, destroyInjury, destroyDeath} = form.value
      addCasualties({
        modelName, isDefault,
        province: provinceId,
        city: cityId,
        nightClass1, dayClass1, nightClass2, dayClass2, nightClass3, dayClass3,
        intactInjury, intactDeath, slightInjury, slightDeath, mediumInjury, mediumDeath, seriousInjury, seriousDeath, destroyInjury, destroyDeath
      }).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      })
    }
  })
}
// 编辑
function editForm() {
  proxy.$refs["casualtiesRef"].validate(valid => {
    if (valid) {
      updateCasualties(form.value).then(response => {
        if (response.message == "修改失败，只能修改自己创建的模型") {
          proxy.$modal.msgWarning(response.message);
        } else {
          proxy.$modal.msgSuccess(response.data);
          open.value = false;
          getList();
        }
      })
    }
  })
}
// 删除
function delForm() {
  const id = form.value.id;
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return delCasualties(id);
  }).then((response) => {
    if (response.message == "删除失败，只能删除自己创建的模型") {
      proxy.$modal.msgWarning(response.message);
    } else {
      proxy.$modal.msgSuccess(response.message);
      open.value = false;
      getList();
    }
  }).catch(() => { })
}

getList()
getProvinceData()
getProvinceFormData()
</script>
<style scoped lang="scss">
.tab-title {
  font-size: 16px;
  font-weight: bold;
  border-left: 4px solid var(--el-color-primary);;
  font-family: PingFangSC-Medium;
  padding-left: 10px;
  margin-bottom: 20px;
}
</style>
<style lang="scss">
.casualties-model-dialog {
  height: 85%;
  overflow: hidden;

  &>.el-dialog__body {
    height: calc(100% - 126px);
    overflow-y: auto;
    padding: 0;

    .el-scrollbar__view {
      padding: 20px;
    }
  }
}
table.casualtiesTable {
  td, th{
    border: 1px solid #c6c6c6;
  }
  th{
    font-weight: 600;
  }
  caption{
    font-weight: 700;
    margin: 10px 0;
  }
  .el-form-item {
    margin: 10px;
  }
}
#lineTd {
  background: #fff url() no-repeat 100% center;
}

#lineTd:after {
  content: '';
  width: 1px;
  height: 100px;
  border-bottom: 1px solid pink;
}
</style>